<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { getApi, updateApi, createApi } from '/@/api/mes/equipment'
import { useInModal } from '/@/hooks/useModal'
import { useSuccessMessage } from '/@/hooks/useMessage'

const props = defineProps(({
  id: String
}))

const emits = defineEmits(['change'])

const modal = useInModal()

const formRef = ref<FormMakerInstance>();
const formProps = reactive<FormMakerProps>({
  name: 'equipmentForm',
  model: {
    id: 0,
    code: '',
    name: '',
  },
  options: [
    { field: "code", label: "设备编号", required: true },
    { field: "name", label: "设备名称", required: true },
  ]
})

const loadViewData = () => {
  if (formProps.model.id) {
    modal.loading(true)
    getApi(formProps.model.id)
      .then(res => {
        Object.assign(formProps.model, res.data)
      })
      .finally(() => modal.loading(false))
  }
}

watch(() => props.id, (id: string) => {
  formProps.model.id = id
  loadViewData()
}, { immediate: true })

const handConfirm = async (btnName: string) => {

  await formRef.value.validate()

  modal.loadingWarp(async () => {
    const postData = {
      ...formProps.model
    }


    if (formProps.model.id) {
      await updateApi(postData)
    } else {
      const { data } = await createApi(postData)
      formProps.model.id = data.id
    }

    useSuccessMessage(btnName + '成功');
    emits('change')
    loadViewData()
  })
}

const viewLayout: ViewLayoutProps = {
  buttons: [
    {
      title: '保存',
      type: 'primary',
      onClick: handConfirm
    },
    { title: '取消', onClick: () => modal.close() },
  ]
}



</script>

<template>
  <ViewLayout v-bind="viewLayout">
    <template #header>
      <FormMaker v-bind="formProps" ref="formRef" />
    </template>
  </ViewLayout>
</template>
